<template>
  <el-dialog v-model="dialogVisible" :title="'租户租赁信息详情'" width="1200px" append-to-body>
    <div class="kuaicenter">
      <div class="kuai"></div>
      <h2>基础信息</h2>
    </div>
    <el-form ref="formRef" v-loading="formLoading" :disabled="disabled" :model="formData" :rules="formRules" label-width="110px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="所在园区" prop="form.parkFoundationInfoId">
            <el-select v-model="formData.form.parkFoundationInfoId" placeholder="请选择所在园区">
              <el-option v-for="item in foundationInfoList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="楼&nbsp;&nbsp;栋&nbsp;&nbsp;号" prop="form.towerNumber">
            <el-input v-model="formData.form.towerNumber" placeholder="请输入楼栋号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所在楼层" prop="form.floor">
            <el-input v-model="formData.form.floor" placeholder="请输入所在楼层" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房&nbsp;&nbsp;间&nbsp;&nbsp;号" prop="form.roomNumber">
            <el-input v-model="formData.form.roomNumber" placeholder="请输入房间号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="建筑面积(㎡)" prop="form.floorArea">
            <el-input v-model="formData.form.floorArea" placeholder="请输入建筑面积(㎡)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间环境" prop="form.roomEnvironment">
            <el-select v-model="formData.form.roomEnvironment" placeholder="请选择房间环境">
              <el-option v-for="dict in parkr_building_room_environment" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间状态" prop="form.roomState">
            <el-select v-model="formData.form.roomState" placeholder="请选择房间状态">
              <el-option v-for="dict in parkbuilingroom_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="对 接 人" prop="form.contactPerson">
            <el-input v-model="formData.form.contactPerson" placeholder="请输入对接人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房屋备注" prop="form.remark">
            <el-input v-model="formData.form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房屋附件" prop="form.attachments">
            <file-upload v-model="formData.form.attachments" placeholder="请输入房屋附件" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>租赁信息</h2>
      </div>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="name">
            <el-input v-model="formData.parkerTenantForm.name" placeholder="请输入承租人" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="缴租频次" prop="parkerTenantForm.frentPaymentFrequency">
            <el-select v-model="formData.parkerTenantForm.frentPaymentFrequency" placeholder="请选择缴租频次">
              <el-option v-for="dict in park_frent_payment_frequency" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租&nbsp;&nbsp;金(元)" prop="parkerTenantForm.rents">
            <el-input v-model="formData.parkerTenantForm.rents" placeholder="请输入租金" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式" prop="parkerTenantForm.contactInformation">
            <el-input v-model="formData.parkerTenantForm.contactInformation" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开始日期" prop="parkerTenantForm.startTime">
            <el-date-picker
              v-model="formData.parkerTenantForm.startTime"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择开始时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束日期" prop="parkerTenantForm.endTime">
            <el-date-picker v-model="formData.parkerTenantForm.endTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租&nbsp;&nbsp;期(天)" prop="parkerTenantForm.leaseTerm">
            <el-input v-model="formData.parkerTenantForm.leaseTerm" placeholder="请输入租期(天)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物业费标准" prop="parkerTenantForm.propertyCostStandard">
            <el-input v-model="formData.parkerTenantForm.propertyCostStandard" placeholder="请输入物业费标准" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租赁备注" prop="parkerTenantForm.remark">
            <el-input v-model="formData.parkerTenantForm.remark" placeholder="请输入租赁备注" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租赁附件" prop="parkerTenantForm.attachments">
            <file-upload v-model="formData.parkerTenantForm.attachments" placeholder="请输入租赁附件" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="退&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;租" prop="parkerTenantForm.surrenderTenancyStatus">
            <el-select v-model="formData.parkerTenantForm.surrenderTenancyStatus" placeholder="请选择退租状态">
              <el-option v-for="dict in park_surrender_tenancy_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="退租时间" prop="parkerTenantForm.rentOutTime">
            <el-date-picker
              v-model="formData.parkerTenantForm.rentOutTime"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择结束时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <div style="font-size: 10px; padding-top: 10px">
            注意：选择退租后，基础信息中的房间状态变为空置房，租赁信息及收租计划将清空，您可在历史租赁信息查看！
          </div>
        </el-col>
      </el-row>
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2 class="text-black">收租计划</h2>
      </div>
      <div>
        <div v-if="formData.rentCollectionPlan.length === 0" style="text-align: right">
          <el-button :loading="buttonLoading" type="primary" @click="handlePush">辅助生成</el-button>
        </div>
        <H2 class="mb-5" style="text-align: center; font-weight: bold">收租计划信息</H2>
        <el-table :data="formData.rentCollectionPlan" style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="dueDate" label="应收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.dueDate" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>

          <el-table-column prop="rentReceivable" label="应收租金(元)">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="collect" label="是否收取" width="160">
            <template #default="scope">
              <el-radio-group v-model="scope.row.collect">
                <el-radio :value="false" size="large">否</el-radio>
                <el-radio :value="true" size="large">是</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="paidInTime" label="实收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.paidInTime" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>
          <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <div v-if="disabled">-</div>
              <div v-else>
                <el-button link type="primary" @click="handlePush"> 新增 </el-button>
                <el-button link type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template v-if="!disabled" #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import {
  getBuilding,
  addBuilding,
  updateBuilding,
  addParkRentCollectionPlan,
  updateParkRentCollectionPlan,
  parkRentCollectionPlanList,
  delParkRentCollectionPlan
} from '@/api/zichanguanli/parkbuilding/index';
import { getTenant, addTenant, updateTenant } from '@/api/zichanguanli/parktenant/index';
import { listFoundationInfoList } from '@/api/zichanguanli/foundationInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { parkbuilingroom_state, parkr_building_room_environment, park_surrender_tenancy_status, park_frent_payment_frequency } = toRefs<any>(
  proxy?.useDict('parkbuilingroom_state', 'parkr_building_room_environment', 'park_surrender_tenancy_status', 'park_frent_payment_frequency')
);

const disabled: any = ref(false); // 表单是否禁用
const buttonLoading = ref(false); // 按钮的 loading
const dialogVisible = ref(false); // 弹窗的是否展示
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改

const formData: any = ref({
  form: {
    parkFoundationInfoId: undefined,
    towerNumber: undefined,
    floor: undefined,
    roomNumber: undefined,
    floorArea: undefined,
    roomEnvironment: undefined,
    roomState: undefined,
    contactPerson: undefined,
    remark: undefined,
    attachments: undefined
  },
  parkerTenantForm: {
    name: undefined,
    frentPaymentFrequency: undefined,
    rents: undefined,
    contactInformation: undefined,
    startTime: undefined,
    endTime: undefined,
    leaseTerm: undefined,
    propertyCostStandard: undefined,
    remark: undefined,
    attachments: undefined,
    surrenderTenancyStatus: undefined,
    rentOutTime: undefined
  },
  rentCollectionPlan: []
});
const formRules = reactive({
  'form.parkFoundationInfoId': [{ required: true, message: '所在园区不能为空', trigger: 'blur' }],
  'form.towerNumber': [{ required: true, message: '楼栋号不能为空', trigger: 'blur' }],
  'form.floor': [{ required: true, message: '所在楼层不能为空', trigger: 'blur' }],
  'form.roomNumber': [{ required: true, message: '房间号不能为空', trigger: 'blur' }],
  'form.floorArea': [{ required: true, message: '建筑面积(㎡)不能为空', trigger: 'blur' }],
  'form.roomEnvironment': [{ required: true, message: '房间环境不能为空', trigger: 'change' }],
  'form.roomState': [{ required: true, message: '房间状态不能为空', trigger: 'change' }],
  'form.contactPerson': [{ required: true, message: '对接人不能为空', trigger: 'change' }],
  'parkerTenantForm.name': [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
  'parkerTenantForm.contactInformation': [{  required: true, message: '请填写正确的手机号码', trigger: 'change' }],
  'parkerTenantForm.frentPaymentFrequency': [{ required: true, message: '缴租频次不能为空', trigger: 'change' }],
  'parkerTenantForm.rents': [{ required: true, message: '租金不能为空', trigger: 'blur' }],
  'parkerTenantForm.startTime': [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  'parkerTenantForm.endTime': [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
});
const formRef = ref(); // 表单 Ref

const handlePush = () => {
  formData.value.rentCollectionPlan.push({
    id: undefined,
    dueDate: undefined,
    rentReceivable: undefined,
    collect: undefined,
    paidInTime: undefined
  });
};

const foundationInfoList: any = ref([]); // 园区基础信息列表
/** 查询园区基础信息列表 */
const getParkList = async () => {
  formLoading.value = true;
  const res = await listFoundationInfoList();
  foundationInfoList.value = res.rows;
  console.log('?? ~ getParkList ~ foundationInfoList.value:', foundationInfoList.value);
  formLoading.value = false;
};

const handleDelete = async (index: number, row: any) => {
  if (row.id) {
    await delParkRentCollectionPlan(row.id);
    formData.value.rentCollectionPlan.splice(index, 1);
  } else {
    formData.value.rentCollectionPlan.splice(index, 1);
  }
};

/** 打开弹窗 */
const open = async (type: string, parkBuildingId?: string | number, parkTenantId?: string | number) => {
  console.log('?? ~ open ~ id:', parkBuildingId);
  getParkList();
  dialogVisible.value = true;
  formType.value = type;
  disabled.value = false;
  resetForm();
  // 修改时，设置数据
  if (type === 'detail') {
    disabled.value = true;
  }
  if (parkBuildingId) {
    formLoading.value = true;
    try {
      const params = {
        parkBuildingId,
        parkRentId: parkTenantId,
        isHistory: true
      };
      const res: any = await getBuilding(params);
      formData.value.form = res.data.parkBuildingBo;
      formData.value.parkerTenantForm = res.data.parkTenantBo || {};
      formData.value.rentCollectionPlan = res.data.parkRentCollectionPlanBo || [];
      // const resLandLease = await getTenant(id);
      // formData.value.initLeaseForm = { ...resLandLease.data };
      // const rentCollectionList = await parkRentCollectionPlanList({
      //   pageSize: 1000,
      //   pageNum: 1,
      //   landInfoId: id
      // });
      // formData.value.rentCollectionPlan = rentCollectionList.rows;
      // console.log('?? ~ open ~ rentCollectionList:', rentCollectionList);
    } finally {
      formLoading.value = false;
    }
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    form: {
      parkFoundationInfoId: undefined,
      towerNumber: undefined,
      floor: undefined,
      roomNumber: undefined,
      floorArea: undefined,
      roomEnvironment: undefined,
      roomState: undefined,
      contactPerson: undefined,
      remark: undefined,
      attachments: undefined
    },
    parkerTenantForm: {
      name: undefined,
      frentPaymentFrequency: undefined,
      rents: undefined,
      contactInformation: undefined,
      startTime: undefined,
      endTime: undefined,
      leaseTerm: undefined,
      propertyCostStandard: undefined,
      remark: undefined,
      attachments: undefined,
      surrenderTenancyStatus: undefined,
      rentOutTime: undefined
    },
    rentCollectionPlan: []
  };
  formRef.value?.resetFields();
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const valid = await formRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    let type = '';
    if (formType.value === 'create') {
      type = 'create';
      const res = await addBuilding(formData.value.form);
      console.log(res);
      formData.value.parkerTenantForm.parkBuildingId = res.data;
      await addTenant(formData.value.parkerTenantForm);
      if (formData.value.rentCollectionPlan.length !== 0) {
        formData.value.rentCollectionPlan.map(async (item: any) => {
          item.parkBuildingId = res.data;
          await addParkRentCollectionPlan(item);
        });
      }
      buttonLoading.value = false;
    } else {
      type = 'update';
      await updateBuilding(formData.value.form);
      await updateTenant(formData.value.parkerTenantForm);
      if (formData.value.rentCollectionPlan.length !== 0) {
        formData.value.rentCollectionPlan.map(async (item: any) => {
          if (item.parkBuildingId) {
            await updateParkRentCollectionPlan(item);
          } else {
            item.parkBuildingId = formData.value.form.id;
            await addParkRentCollectionPlan(item);
          }
        });
      }
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success', type);
  } finally {
    formLoading.value = false;
  }
};
</script>
